package org.arch_learn.redis.jedis;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class JedisTest {

    public static void main(String[] args) {
//        Jedis jedis = new Jedis("127.0.0.1", 6379);
//        jedis.set("key1", "value1");
//        System.out.println(jedis.get("key1"));
//        jedis.lpush("list1", "1", "2", "3", "4", "5");
//        System.out.println(jedis.llen("list1"));

        Jedis jedis = new Jedis("127.0.0.1", 6379);

        //预先在redis里设置该key的value为0;
        String flashSaleKey = "flash_sale_key";

        jedis.watch(flashSaleKey);

        ExecutorService executorService = Executors.newFixedThreadPool(20);

        for (int i = 0; i < 1000; i++) {
            executorService.execute(() -> {
                try {
                    jedis.watch(flashSaleKey);
                    Object objVal = jedis.get(flashSaleKey);
                    Integer intVal = Integer.valueOf((String) objVal);
                    String uid = UUID.randomUUID().toString().replaceAll("-", "");
                    if (intVal < 20) {
                        Transaction tx = jedis.multi();
                        jedis.incr(flashSaleKey);
                        List<Object> exec = tx.exec();
                        if (exec != null && !exec.isEmpty()) {
                            System.out.println("用户：" + uid + "秒杀成功！");
                        } else {
                            System.out.println("用户：" + uid + "秒杀失败！");
                        }
                    } else {
                        System.out.println("秒杀活动结束！感谢用户：" + uid + "参与活动！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    jedis.close();
                }
            });
        }
        executorService.shutdown();
    }
}
